package com.ebt.m.customer.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.commons.utils.ActivityUtils;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.entity.CustomerAttaName;
import com.ebt.m.customer.event.EventCustomerAllPageIndex;
import com.ebt.m.customer.event.EventRefreshAttachment;
import com.ebt.m.customer.net.json.CustomerCRUDRetJson;
import com.ebt.m.customer.ui.ActivityAttachmentDoload;
import com.ebt.m.customer.ui.ActivityCustomerAll;
import com.ebt.m.customer.util.AttachmentUtil;
import com.ebt.m.customer.util.ToastUtil;
import com.ebt.m.data.entity.EntityCustomerAttachment;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.proposal_v2.widget.dialog.EBTBottomDialogBase;
import com.ebt.m.utils.DataValidation;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.utils.fileutils.FileUtils;
import com.tendcloud.tenddata.TCAgent;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


/**
 * @author Damon
 * @date 2017/12/1
 */

public class Dialog4CustomerAttachmentOperate extends EBTBottomDialogBase {
    private EntityCustomerAttachment entityCustomerAttachment;
    private Context mContext;

    public static Dialog4CustomerAttachmentOperate netInstance(EntityCustomerAttachment entityCustomerAttachment) {
        Dialog4CustomerAttachmentOperate dialog4CustomerAttachment = new Dialog4CustomerAttachmentOperate();
        Bundle extras = new Bundle();
        extras.putSerializable(Arg_Data, entityCustomerAttachment);
        dialog4CustomerAttachment.setArguments(extras);
        return dialog4CustomerAttachment;
    }

    @Override
    public void init() {
        mContext = getContext();
        entityCustomerAttachment = (EntityCustomerAttachment) getArguments().getSerializable(Arg_Data);
        if (entityCustomerAttachment != null) {
            setTitle(entityCustomerAttachment.fileName);
        }
        View mainView = LayoutInflater.from(getContext()).inflate(R.layout.layout_customer_attachment_operate, null, false);
        View viewOpen = mainView.findViewById(R.id.btn_open);
        View viewDownload = mainView.findViewById(R.id.btn_download);
        View viewRename = mainView.findViewById(R.id.btn_rename);
        View viewRemove = mainView.findViewById(R.id.btn_remove);

        File f = new File(AttachmentUtil.netPathToLocalPath(entityCustomerAttachment.path, CustomerConstant.Attachment.DIR_PATH + File.separator));
        if (f.exists()) {
            viewOpen.setVisibility(View.VISIBLE);
            viewDownload.setVisibility(View.GONE);
        } else {
            viewOpen.setVisibility(View.GONE);
            viewDownload.setVisibility(View.VISIBLE);
        }
        viewOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //打开
                File f = new File(AttachmentUtil.netPathToLocalPath(entityCustomerAttachment.path, CustomerConstant.Attachment.DIR_PATH + File.separator));
                if (f.exists()) {
                    try {
                        FileUtils.openFile(getContext(), f);
                    } catch (Exception e) {
                        UIHelper.makeToast(mContext, "无法打开此文件格式");
                        e.printStackTrace();
                    }
                }
                dismiss();
            }
        });
        viewDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //下载
                Intent intent = new Intent(getContext(), ActivityAttachmentDoload.class);
                intent.putExtra("data", entityCustomerAttachment);
                getContext().startActivity(intent);
                dismiss();
            }
        });
        viewRename.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //重命名
                toRename();
            }
        });
        viewRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (entityCustomerAttachment == null) {
                    return;
                }
                //删除
                EBTAPI ebtapi = AppInitService.getEbtApi();
                ebtapi.deleteAtta(entityCustomerAttachment.getUuid()).compose(RxUtil.rxSchedulerHelper()).subscribe(getAttaCURSubscriber(entityCustomerAttachment));
            }
        });
        addDialogBody(mainView);
        setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
    }

    /**
     * 区分在线文件和本地文件
     */
    private void toRename() {
        if (DataValidation.isEmpty(entityCustomerAttachment.fileName)) {
            return;
        }
        String suffix = FileUtils.getSuffixFromUrl(entityCustomerAttachment.fileName);
        Dialog4CustomerAttachmentRename dialog = Dialog4CustomerAttachmentRename.netInstance(entityCustomerAttachment.fileName);
        dialog.setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismissAllowingStateLoss();
            }
        });
        dialog.setPositiveButton("确定", v -> {
            View view = dialog.getmContentView();
            if (view == null) {
                return;
            }
            EditText mETFileName = (EditText) view.findViewById(R.id.customer_add_attachment_dialog_file_name_et);
            String newFileName = mETFileName.getText().toString().trim();
            if (DataValidation.isEmpty(newFileName)) {
                UIHelper.hideSoftInputFromWindow(mETFileName);
                dialog.dismissAllowingStateLoss();
                dismiss();
                return;
            }
            newFileName += suffix;
            if (newFileName.equalsIgnoreCase(entityCustomerAttachment.getFileName())) {
                UIHelper.hideSoftInputFromWindow(mETFileName);
                UIHelper.makeToast(getContext(), "相同的文件名");
                return;
            }
//            File f = new File(AttachmentUtil.netPathToLocalPath(entityCustomerAttachment.path, CustomerConstant.Attachment.DIR_PATH + File.separator));
//            if (f.exists()) {
//                //本地文件先修改本地文件的名称
//                try {
//                    FileUtils.changeFileName(f.getAbsolutePath(), FileUtils.getFilePath(f.getAbsolutePath()) + File.separator + newFileName);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
            CustomerAttaName customerAttaName = new CustomerAttaName();
            customerAttaName.fileName = newFileName;
            //在线文件直接调用接口
            EBTAPI ebtapi = AppInitService.getEbtApi();
            ebtapi.updateAttaName(entityCustomerAttachment.getUuid(), customerAttaName).compose(RxUtil.rxSchedulerHelper()).subscribe(new Observer<CustomerCRUDRetJson>() {
                @Override
                public void onComplete() {

                }

                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                    UIHelper.makeToast(getContext(), "重命名失败");
                }

                @Override
                public void onNext(CustomerCRUDRetJson customerCRUDRetJson) {
                    if (customerCRUDRetJson != null && customerCRUDRetJson.data != null && customerCRUDRetJson.data.attachmentId != null) {
                        UIHelper.makeToast(getContext(), "重命名成功");
                        //更新
                        EventBus.getDefault().post(new EventRefreshAttachment(true));
                        EventBus.getDefault().post(new EventCustomerAllPageIndex(4));
                        dialog.dismissAllowingStateLoss();
                        dismiss();
                    }
                }
            });

        });
        ActivityCustomerAll activityCustomerAll = (ActivityCustomerAll) mContext;
        if (activityCustomerAll != null) {
            FragmentTransaction ft = activityCustomerAll.getSupportFragmentManager().beginTransaction();
            ft.add(dialog, "change_file_name");
            ft.commitAllowingStateLoss();
        }
    }


    private Observer<CustomerCRUDRetJson> getAttaCURSubscriber(EntityCustomerAttachment attachment) {

        return new Observer<CustomerCRUDRetJson>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onComplete() {
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.showToast(mContext.getString(R.string.network_fail));
            }

            @Override
            public void onNext(CustomerCRUDRetJson customerCreateRetJson) {
                if (customerCreateRetJson == null) {
                    ToastUtil.showToast(mContext.getString(R.string.network_fail));
                    return;
                }
                if (customerCreateRetJson.error != null) {
                    ToastUtil.showToast(mContext.getString(R.string.network_fail));
                    return;
                }
                if (customerCreateRetJson.error == null) {
                    if (customerCreateRetJson.data == null) {
                        ToastUtil.showToast(mContext.getString(R.string.network_fail));
                        return;
                    } else {
                        File file = new File(AttachmentUtil.netPathToLocalPath(attachment.path, CustomerConstant.Attachment.DIR_PATH + File.separator));
                        if (file != null && file.exists()) {
                            file.delete();
                        }
                        ToastUtil.showToastD("附件删除成功");
                        TCAgent.onEvent(mContext, "attachment_operation", "delete");
                        EventBus.getDefault().post(new EventRefreshAttachment(true));
                        EventBus.getDefault().post(new EventCustomerAllPageIndex(4));
                        dismiss();
                    }
                }
            }
        };
    }

    @Override
    public void onResume() {
        super.onResume();
        int dialogHeight = (int) (ActivityUtils.getScreenSize(getActivity())[1] * 0.5);
        resetDialogHeight(dialogHeight);
        setPositiveShown(false);
    }
}
